package org.finesys.common.security.core.support;

import cn.hutool.core.util.ArrayUtil;
import org.finesys.common.security.core.util.SecurityUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.util.PatternMatchUtils;
import org.springframework.util.StringUtils;

import java.util.Collection;

/**
 * 权限校验工具
 */
public class PermissionService {

    public boolean hasPermission(String... permissions) {
        if (ArrayUtil.isEmpty(permissions)) {
            return false;
        }
        Authentication authentication = SecurityUtils.getAuthentication();
        if (authentication == null) {
            return false;
        }
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        return authorities.stream().map(GrantedAuthority::getAuthority)
                .filter(StringUtils::hasText)
                .anyMatch(s -> PatternMatchUtils.simpleMatch(permissions, s));
    }

}
